using System.Collections;
using System.Collections.Generic;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.AI;

public class NavPathLineRenderer : MonoBehaviour
{
    [SerializeField] private float pathHeightOffset = 0.1f;   // 绘制路径时的垂直偏移量（在地面上方）
    [SerializeField] private int quality = 10;           // 每个路径段的分段数
    [SerializeField] private float maxHeight = 10;       // 射线最大高度
    [SerializeField] private float drawUpdateSpeed = 0.2f;   // 路径绘制更新速度，越大效果越好但是越费性能
    [SerializeField] private LayerMask layerMask;
    private Vector3 targetPosition; // 目标点
    public bool isMove;//是否开始移动
    private LineRenderer line;
    private Coroutine drawCoroutine;
    private RaycastHit hitInfo;
    private NavMeshAgent agent;
    private SoldierObj soldierObj;
     List<Vector3> newPath = new List<Vector3>();   // 存储平滑后的路径点
    private void Start()
    {
        soldierObj = GetComponent<SoldierObj>();
        isMove = false;
        line = GetComponentInChildren<LineRenderer>();
        agent = GetComponent<NavMeshAgent>();

        // 在开始之前停止任何现有的协程
        if (drawCoroutine != null)
        {
            StopCoroutine(drawCoroutine);
        }
        drawCoroutine = StartCoroutine(DrawNavMeshLine());
    }

    // void Update()
    // {
    //     if (Input.GetMouseButtonDown(1))
    //     {
    //         //获取目标点 通过射线检测
    //         if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 1000, layerMask))
    //         {
    //             targetPosition = hitInfo.point;
    //             isMove = true;
    //         }
    //     }
    // }
    public void StartDraw(Vector3 point)
    {
        isMove = true;
        targetPosition = point;
    }

    // 协程：持续绘制NavMesh路径
    private IEnumerator DrawNavMeshLine()
    {
        WaitForSeconds wait = new WaitForSeconds(drawUpdateSpeed);   // 等待时间间隔
        NavMeshPath path = new NavMeshPath();   // 存储计算路径的NavMeshPath对象

        while (true)
        {
            if (isMove)
            {
                // 从玩家位置到目标位置计算路径
                if (NavMesh.CalculatePath(transform.position, targetPosition, NavMesh.AllAreas, path))
                {
                    newPath.Clear();

                    for (int i = 0; i < path.corners.Length - 1; i++)
                    {
                        Vector3 currentPoint = path.corners[i] + Vector3.up * maxHeight;   // 当前路径段起始点
                        Vector3 nextPoint = path.corners[i + 1] + Vector3.up * maxHeight;  // 下一个路径段起始点

                        // 细分路径段并向下射线，寻找有效的地面点
                        for (int j = 0; j <= quality; j++)
                        {
                            Vector3 calPoint = Vector3.Lerp(currentPoint, nextPoint, (1f / quality) * j);   // 计算插值点
                            RaycastHit hit;

                            // 射线向下，寻找地面点
                            if (Physics.Raycast(calPoint, Vector3.down, out hit, Mathf.Infinity, layerMask))//设置为 Mathf.Infinity,射线会无限延伸直到碰到符合条件的碰撞体
                            {
                                newPath.Add(hit.point);   // 将有效的地面点添加到平滑路径中
                            }
                        }
                    }

                    // 设置LineRenderer的位置数量和位置
                    line.positionCount = newPath.Count;
                    for (int i = 0; i < newPath.Count; i++)
                    {
                        // 每个位置设置在地面上方的偏移量处
                        line.SetPosition(i, newPath[newPath.Count - 1 - i] + Vector3.up * pathHeightOffset);
                    }

                    // 设置玩家的NavMeshAgent路径为计算出的路径，开始移动
                    agent.SetPath(path);
                    soldierObj.SetRun(true);
                    soldierObj.SetAttack(false);

                    // 到达目标位置，停止计算，节约性能
                    if (!agent.pathPending && agent.remainingDistance <= 0.1f)
                    {
                        line.positionCount = 0;
                        isMove = false;
                        if (soldierObj.target != null && soldierObj.target.GetComponent<Collectable>())
                        {
                            soldierObj.Attack();
                        }
                        else
                        {
                            soldierObj.SetRun(false);
                            soldierObj.SetAttack(false);
                        }
                    }
                }
                else
                {
                    isMove = false;
                    soldierObj.SetRun(false);
                    soldierObj.SetAttack(false);
                    line.positionCount = 0;
                    // 清除当前路径
                    agent.ResetPath();
                }
            }

            yield return wait;   // 等待下一次更新
        }
    }
}